package com.wsz.ucenter.config;


import com.wsz.ucenter.utils.ApplicationContextUtils;
import com.wsz.ucenter.utils.RedisUtils;
import org.apache.ibatis.cache.Cache;
import org.springframework.data.redis.connection.RedisServerCommands;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.util.DigestUtils;

public class RedisCache implements Cache {
    private final String id; //mapper 的namespace
    private RedisUtils redisUtils;

    public RedisCache(String id) {
        this.id = id;
    }

    private RedisUtils getRedisUtils() {
        if(this.redisUtils == null){
            RedisUtils redisUtils = (RedisUtils) ApplicationContextUtils.getBean("redisUtils");
            this.redisUtils = redisUtils;
            return redisUtils;
        }else return this.redisUtils;
    }

    private String getKeyToMd5(Object key1){
        String key = key1.toString();
        //算法工具集
        return DigestUtils.md5DigestAsHex(key.getBytes());
    }

    @Override
    public String getId() {
        return this.id;
    }

    @Override
    public void putObject(Object key, Object value) {
        getRedisUtils();
        System.out.println("id: "+ id +" key: " + key + "value: " + value);

        redisUtils.hset(id,getKeyToMd5(key),value);
    }

    @Override
    public Object getObject(Object key) {
        getRedisUtils();
        System.out.println(redisUtils.hget(id,getKeyToMd5(key)));
        return redisUtils.hget(id,getKeyToMd5(key));
    }

    @Override
    public Object removeObject(Object key) {
        getRedisUtils();
        System.out.println("key: " + key);
        redisUtils.hdel(id,getKeyToMd5(key));
        return null;
    }

    @Override
    public void clear() {
        System.out.println("id: "+id);
        getRedisUtils();
        redisUtils.del(id);
    }

    @Override
    public int getSize() {
        getRedisUtils();
        Long size = (Long)redisUtils.execute((RedisCallback<Long>) RedisServerCommands::dbSize);
        return size.intValue();
    }
}